import React from 'react';
import {
  ViewPropTypes,
  Text,
  StyleSheet,
  View,
  Modal,
  TouchableWithoutFeedback,
  ActivityIndicator
} from 'react-native';

export interface LoadingProps {
  loading: boolean;
  text?: string;
  onCancel?: () => void;
  destroy?: () => void;
  [key: string]: any;
}

export default class LoadingView extends React.Component<LoadingProps> {
  static displayName = 'LoadingView';

  static defaultProps = {
    loading: true,
    text: null
  };

  state = {
    show: true
  };

  hide = () => {
    this.setState({ show: false }, () => {
      const { destroy } = this.props;
      destroy && setTimeout(() => destroy(), 100);
    });
  };

  _onPressLoading = () => {
    const { onCancel } = this.props;
    onCancel?.();
  };

  render() {
    const { loading, text } = this.props;
    const shouldShowLoading = loading && this.state.show;

    return (
      <Modal
        animationType="fade"
        transparent={true}
        visible={shouldShowLoading}
        onRequestClose={this._onPressLoading}
        supportedOrientations={['landscape', 'portrait']}
      >
        <View style={styles.mask}>
          <TouchableWithoutFeedback onPress={this._onPressLoading}>
            <View style={styles.loadingBg}>
              <ActivityIndicator size="large" color="white" />
              {text ? (
                <Text
                  style={styles.loadingText}
                  selectable={false}
                  numberOfLines={2}
                  ellipsizeMode="tail"
                >
                  {text}
                </Text>
              ) : null}
            </View>
          </TouchableWithoutFeedback>
        </View>
      </Modal>
    );
  }
}

const styles = StyleSheet.create({
  mask: {
    backgroundColor: 'transparent',
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center'
  },
  loadingBg: {
    width: 120,
    height: 120,
    borderRadius: 8,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#333333'
  },
  loadingText: {
    fontSize: 14,
    lineHeight: 20,
    marginHorizontal: 8,
    marginTop: 10,
    color: 'white',
    textAlign: 'center'
  }
});
